<template>
  <el-dialog v-model="visible" :title="title" width="600px">
    <el-form :model="formData" :rules="rules" ref="formRef" label-width="120px">

      <!-- ID 字段（隐藏） -->
      <input type="hidden" v-model="formData.id" />

      <!-- 名称 -->
      <el-form-item label="权限名称" prop="name" v-if="showFields.name">
        <el-input v-model="formData.name" />
      </el-form-item>

      <!-- 编码 -->
      <el-form-item label="权限编码" prop="code" v-if="showFields.code">
        <el-input v-model="formData.code" placeholder="如: user.add / role.edit" />
      </el-form-item>

      <!-- 类型 -->
      <el-form-item label="权限类型" prop="type" v-if="showFields.type">
        <el-select v-model="formData.type" style="width: 100%">
          <el-option label="菜单权限" :value="1" />
          <el-option label="接口权限" :value="2" />
        </el-select>
      </el-form-item>

      <!-- 请求方法 -->
      <!-- FIXME 这里做下拉选项，接口类的权限给方法、接口路径选项 -->
      <el-form-item label="请求方法" prop="method" v-if="showFields.method && isApiPermission">
        <el-select v-model="formData.method" style="width: 100%">
          <el-option label="GET" value="GET" />
          <el-option label="POST" value="POST" />
          <el-option label="PUT" value="PUT" />
          <el-option label="DELETE" value="DELETE" />
          <el-option label="PATCH" value="PATCH" />
        </el-select>
      </el-form-item>

      <!-- 接口路径 -->
      <el-form-item label="接口路径" prop="path" v-if="showFields.path && isApiPermission">
        <el-input v-model="formData.path" placeholder="/api/user" />
      </el-form-item>


      <!-- 描述 -->
      <el-form-item label="描述信息" prop="description" v-if="showFields.description">
        <el-input v-model="formData.description" type="textarea" :rows="3" placeholder="请输入权限描述" />
      </el-form-item>

      <!-- 排序 -->
      <el-form-item label="排序" prop="order_num" v-if="showFields.order_num">
        <el-input-number v-model="formData.order_num" :min="0" style="width: 100%" />
      </el-form-item>

      <!-- 是否隐藏 -->
      <el-form-item label="是否隐藏" prop="hidden" v-if="showFields.hidden">
        <el-switch v-model="formData.hidden" :active-value="1" :inactive-value="0" />
      </el-form-item>

    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {funPick} from "@/utils/common";

// ====================
// Props 定义与 Emits
// ====================
const props = defineProps({
  modelValue: Boolean,
  formData: {
    type: Object,
    default: () => ({})
  },
  // 控制显示哪些字段
  fields: {
    type: Object,
    default: () => ({
      name: true,
      code: true,
      type: true,
      method: true,
      path: true,
      description: true,
      order_num: true,
      hidden: true,
      parent_id: true
    })
  },
  // 可选的权限树数据（用于父级选择）
  permissionTree: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'submit'])

// ====================
// 响应式数据初始化
// ====================
const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const title = computed(() => (formData.value.id ? '编辑权限' : '新增权限'))

const formRef = ref(null)
const formData = ref({ ...props.formData })

// 显示的字段控制
const showFields = computed(() => ({
  name: props.fields.name !== false,
  code: props.fields.code !== false,
  type: props.fields.type !== false,
  method: props.fields.method !== false,
  path: props.fields.path !== false,
  description: props.fields.description !== false,
  order_num: props.fields.order_num !== false,
  hidden: props.fields.hidden !== false,
  parent_id: props.fields.parent_id !== false
}))

// ====================
// 表单初始化逻辑
// ====================
watch(
  () => props.formData,
  (val) => {
    formData.value = val
        ? funPick(val, ['id', 'name', 'code', 'type', 'method', 'path', 'description'])
        :  {
          name: '',
          code: '',
          type: 1,
          method: '',
          path: '',
          description: ''
        }
  },
  { immediate: true }
)

// 判断是否为接口权限
// FIXME 这里做下拉选项，接口类的权限给方法、接口路径选项
const isApiPermission = computed(() => formData.value.type === 2)


// ====================
// 表单验证规则
// ====================
const rules = {
  name: [
    { required: showFields.value.name, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符之间', trigger: 'blur' }
  ],
  code: [
    { required: showFields.value.code, message: '请输入权限编码', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_\.-]+$/, message: '编码只能包含字母、数字、下划线、点和横线', trigger: 'blur' }
  ],
  type: [
    { required: showFields.value.type, message: '请选择权限类型', trigger: 'change' }
  ],
  method: [
    {required: isApiPermission.value, message: '请选择请求方法', trigger: 'change' }
  ],
  path: [
    // FIXME 这里做下拉选项，接口类的权限给方法、接口路径选项
    { required: isApiPermission.value, message: '请输入接口路径', trigger: 'blur' },
    { pattern: /^\/.*$/, message: '路径必须以斜杠开头', trigger: 'blur' }
  ]
}

// ====================
// 提交处理
// ====================
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    emit('submit', formData.value)
    visible.value = false
  } catch (error) {
    ElMessage.error('请填写完整且符合要求的权限信息')
  }
}
</script>